package cn.vihub.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.vihub.param.ShopRoleParam;
import cn.vihub.pojo.ShopRole;
import cn.vihub.service.ShopRoleService;
import cn.vihub.service.ShopRoleToMenuService;
import cn.vihub.service.ShopUserToRoleService;
import cn.vihub.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
* 角色数据表(shop_role)表控制层
*
* @author xxxxx
*/
@RestController
@RequestMapping("/shop-user/role")
public class RoleController {
/**
* 服务对象
*/
    @Autowired
    private ShopRoleService shopRoleService;

    @Autowired
    private ShopUserToRoleService shopUserToRoleService;

    @Autowired
    private ShopRoleToMenuService shopRoleToMenuService;


    @GetMapping("selectPageByRole")
    public Result<IPage<ShopRole>> selectPageByRole(ShopRoleParam shopRoleParam){
        return Result.success(shopRoleService.selectPage(shopRoleParam));
    }


    /**
     * @author: 秋晚
     * @description:保存角色
     * @params: [cn.vihub.param.ShopRoleParam]
     * @return: cn.vihub.utils.Result<java.lang.Boolean>
     * @date: 2025/7/19 11:47
     */
    @PostMapping("saveRole")
    public Result<Boolean> saveRole(@RequestBody ShopRoleParam shopRoleParam){
        if(ObjectUtil.isEmpty(shopRoleParam.getId())){
            shopRoleParam.setCreateTime(new Date());
        }else{
            shopRoleParam.setUpdateTime(new Date());
        }
        //创建一个新的对象
        ShopRole shopRole = new ShopRole();
        //拷贝
        BeanUtils.copyProperties(shopRoleParam,shopRole);
        //返回数据
        return shopRoleService.saveOrUpdate(shopRole)? Result.success(): Result.error(500,"添加角色失败!");
    }


    /**
     * @author: 秋晚
     * @description:删除角色
     * @params: [java.lang.Integer]
     * @return: cn.vihub.utils.Result<java.lang.Boolean>
     * @date: 2025/7/19 11:47
     */
    @DeleteMapping("deleteRoleById/{id}")
    public Result<Boolean> deleteRoleById(@PathVariable(name = "id") Integer id){

        //删除前检验角色下是否有关联用户
        shopUserToRoleService.isUserByRoleId(id);
        if(shopRoleService.removeById(id)){
            //删除角色下的权限
            shopRoleToMenuService.removebyRoleId(id);
            //删除成功
            return Result.success();
        }else{
            return Result.error(500,"删除失败!");
        }
    }


    /**
     * @author: 秋晚
     * @description:角色绑定权限
     * @params: [java.lang.Integer]
     * @return: cn.vihub.utils.Result<java.lang.Boolean>
     * @date: 2025/7/19 11:51
     */
    @PostMapping("bindMenu")
    public Result<Boolean> bindMenu(@RequestBody ShopRoleParam shopRoleParam){
        return Result.success(shopRoleService.bindMenu(shopRoleParam));
    }
}
